﻿package visualizer.code
{
	import flash.geom.ColorTransform;
	import flash.events.Event;
	import flash.display.MovieClip;
	
	public class BradVisualizer extends Visualizer
	{
		// Variables
		var volcano:Volcano;
		var fireHolder:MovieClip;
		var id:uint;
		var fire:Fire;
		
		public function BradVisualizer()
		{
			// Initialize Volcano
			volcano = new Volcano();
			addChild(volcano);
			
			// ID used to name new instances of Fire
			id = 0;
			
			// Initialize Fire Holder
			fireHolder = volcano.getChildByName("FireHolder") as MovieClip;
			
			// Setup Listeners
			addEventListener(Event.ENTER_FRAME,onEnterFrame);
			addEventListener(BeatEvent.LOW_BAND_BEAT, handleLowBeat);
			addEventListener(BeatEvent.MID_BAND_BEAT, handleMidBeat);
			addEventListener(BeatEvent.HIGH_BAND_BEAT, handleHighBeat);
		}
		
		override protected function drawFrame()
		{
			// Show the frame that corresponds to the volume of playback
			gotoAndStopByVol(volcano);
		}
		
		private function onEnterFrame(e:Event)
		{
			// Remove any fire objects that have finished playing
			for(var i:uint=1;i<fireHolder.numChildren;i++)
			{
				var child = fireHolder.getChildAt(i) as MovieClip;
				if(child.currentFrame == child.totalFrames) fireHolder.removeChild(child);
			}
		}
		
		private function handleLowBeat(event:BeatEvent)
		{
			// Create an instance of fire and set it's properties
			var fire:Fire = new Fire();
			fire.x = 250;
			fire.y = 200;
			fire.alpha = .75;
			fireHolder.addChild(fire);
		}
		
		private function handleMidBeat(event:BeatEvent)
		{
			// Create an instance of fire and set it's properties
			var fire:Fire = new Fire();
			fire.x = 300;
			fire.y = 200;
			fire.alpha = .75;
			fireHolder.addChild(fire);
		}
		
		private function handleHighBeat(event:BeatEvent)
		{
			// Create an instance of fire and set it's properties
			var fire:Fire = new Fire();
			fire.x = 350;
			fire.y = 200;
			fire.alpha = .75;
			fireHolder.addChild(fire);
		}
		
		//---------- Convenience Functions ----------//		
		private function random(low:Number=0, high:Number=1):Number
		{
			return Math.floor(Math.random() * (1+high-low)) + low;
		}		
		
		private function gotoAndStopByVol(anim:MovieClip)
		{
			var newFrame:uint = Math.floor((avgVol()*anim.totalFrames)/.9);
			if(newFrame > anim.totalFrames) newFrame = anim.totalFrames;
			anim.gotoAndStop(newFrame);
		}
	}
}